import { Space, Button, message, } from 'antd';
import ProCard from '@ant-design/pro-card';
import React, { useState, useRef, useEffect } from 'react';
import { getDvaApp, history, } from 'umi';
import ProForm, {
    ProFormText,
    ProFormDatePicker,
    ProFormTextArea,
    ProFormDigit,
} from '@ant-design/pro-form';
import type { ProFormInstance } from '@ant-design/pro-form';
import { PageContainer } from '@ant-design/pro-layout';
import $utils from '@/utils/utils';
import { AgentCreate, AgentUpdate, getAgentDetail } from '@/services/agent';

const Detail: React.FC = () => {

    // 解决无法调用dispatch
    const dispatch = getDvaApp()._store.dispatch;
    const formRef = useRef<ProFormInstance>();
    const [cur_id, setCur_id] = useState<string>();
    const [agentDetail, setAgentDetail] = useState<any>();



    const l_state: any = history.location.state;
    if (!cur_id && !l_state) {
        history.push('/BasicConfig/AgentManage');
    }

    const id: string = l_state?.data?.id || '';
    //  同path更新,只更新state时，通过id重新请求数据
    if ((l_state && id) && (!cur_id || cur_id !== id)) {
        setCur_id(id);
    } else if (l_state && !id && cur_id !== id) {
        setCur_id('');
    }

    const isCreate: boolean = l_state?.status === 'create';
    const isUpdate: boolean = l_state?.status === 'update';


    // 快递公司列表
    useEffect(() => {
        // 获取柜体详情
        const getAgentDetails = async () => {
            try {
                const msg = await getAgentDetail({ id: cur_id });;
                if (msg.code === 0) {
                    const detail = (msg.body);
                    setAgentDetail(detail);
                    formRef && formRef.current?.resetFields();
                    return;
                }
            } catch (error) {
                console.log(error);
            }
        };
        if (!cur_id) {
            setAgentDetail(undefined);
            formRef && formRef.current?.resetFields();
        }
        else {
            getAgentDetails();
            formRef && formRef.current?.resetFields();
            return;
        }
    }, [cur_id]);

    return (
        <PageContainer>
            {(isCreate || agentDetail) && <ProCard style={{ marginTop: 8 }} gutter={8} >
                <ProForm
                    labelCol={{ span: 4 }}
                    wrapperCol={{ span: 16 }}
                    layout={"horizontal"}
                    formRef={formRef}
                    initialValues={isCreate ? undefined : agentDetail}
                    onFinish={async (values) => {
                        let params = { ...values };
                        if (isCreate) {
                            params = Object.assign(params, { name: values.name });
                            const msg = await AgentCreate(params);
                            if (msg.code === 0) {
                                message.success('新增成功', 1, () => {
                                    // 设置当前tab对象
                                    $utils.setNewTab(dispatch, { name: '代理商管理', path: '/BasicConfig/AgentManage', isTopMenu: true });
                                    history.push('/BasicConfig/AgentManage');
                                });
                            }
                        }
                        else if (isUpdate) {
                            params = Object.assign(params, { id: cur_id });
                            const msg = await AgentUpdate(params);
                            if (msg.code === 0) {
                                message.success('编辑成功', 1, () => {
                                    // 设置当前tab对象
                                    $utils.setNewTab(dispatch, { name: '代理商管理', path: '/BasicConfig/AgentManage', isTopMenu: true });
                                    history.push('/BasicConfig/AgentManage');
                                });
                            }
                        }
                    }}
                    submitter={{
                        render: (props, doms) => {
                            return [
                                <Space style={{ marginLeft: '16.66666667%' }}>
                                    <Button type="primary" htmlType="submit">保存</Button>
                                    <Button onClick={() => {
                                        // 设置当前tab对象
                                        $utils.setNewTab(dispatch, { name: '代理商管理', path: '/BasicConfig/AgentManage', isTopMenu: true });
                                        history.push('/BasicConfig/AgentManage');
                                    }}>取消</Button>
                                </Space>
                            ]
                        }
                    }}
                >
                    <ProFormText
                        width={'md'}
                        name="name"
                        label={'代理商名称'}
                        disabled={!isCreate}
                        fieldProps={{
                            maxLength: 100
                        }}
                        rules={[
                            {
                                required: true,
                            },
                        ]}
                    />
                    <ProFormDigit
                        width={'md'}
                        name="code"
                        label={'代理商代码'}
                        disabled={!isCreate}
                        max={99}
                        fieldProps={{
                            controls: false,
                        }}
                        rules={[
                            {
                                required: true,
                            },
                        ]}
                    />
                    <ProFormText
                        width={'md'}
                        name="contact"
                        label={'代理商联系人'}
                        fieldProps={{
                            maxLength: 30
                        }}
                        rules={[
                            {
                                required: true,
                            },
                        ]}
                    />
                    <ProFormText
                        width={'md'}
                        name="phone"
                        label={'代理商手机号'}
                        fieldProps={{
                            maxLength: 11,
                        }}
                        rules={[
                            {
                                required: true,
                            },
                        ]}
                    />
                    <ProFormDatePicker
                        name="effectDate"
                        label={'订单生效日期'}
                        rules={[
                            {
                                required: true,
                            }
                        ]}
                    />
                    <ProFormTextArea
                        name="remark"
                        label="备注"
                        placeholder="选填，请输入备注信息"
                    />
                </ProForm>
            </ProCard>}
        </PageContainer>
    );
};

export default Detail;
